<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use \app\admin\model\Equity as EquityOrder;
use \app\admin\model\share\CommonShare;
use app\common\model\User;

/**
 * 示例接口
 */
class Equity extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new EquityOrder;
    }

    /**
     * 核销接口，验证提货劵是否有效
     */
    public function writeoff()
    {
        $code =  $this->request->post("code"); // ID
        $mobile = $this->request->post("mobile");
        $row = $this->model->get(['code'=>$code, 'status'=>0]);
        if (empty($row)) {
            $this->error("权益包不存在");
        }
        if (!$mobile) {
            $this->error(__('手机号不能为空'));
        }
        
        $fttuser =  User::getByMobile($mobile);
        if (empty($fttuser)) {
            $result =$this->model->where(['code' =>$code])->update(['status'=>1, 'receive_mobile'=>$mobile]);
        } else {
            (new CommonShare())->add_share_order_equity($row->money,$row->goods_id,$fttuser->id);
            $result =$this->model->where(['code' =>$code])->update(['status'=>2, 'receive_mobile'=>$mobile,'user_id'=>$fttuser->id]);
        }
        $this->success('成功', $result);
    }
}
